
package com.jf.cloud.search.controller.platform;

import cn.hutool.core.collection.CollUtil;
import com.jf.cloud.api.dto.EsPageDTO;
import com.jf.cloud.api.multishop.feign.ShopDetailFeignClient;
import com.jf.cloud.api.multishop.vo.ShopDetailVO;
import com.jf.cloud.api.supplier.feign.SupplierDetailFeignClient;
import com.jf.cloud.api.supplier.vo.SupplierApiDetailVO;
import com.jf.cloud.api.vo.EsPageVO;
import com.jf.cloud.common.cache.constant.CacheNames;
import com.jf.cloud.common.cache.util.RedisUtil;
import com.jf.cloud.common.product.constant.SupplierSpuType;
import com.jf.cloud.common.product.dto.ProductSearchDTO;
import com.jf.cloud.common.product.vo.search.ProductSearchVO;
import com.jf.cloud.common.product.vo.search.SearchSpuTagVO;
import com.jf.cloud.common.product.vo.search.SpuAdminVO;
import com.jf.cloud.common.product.vo.search.SpuSearchVO;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.search.constant.EsConstant;
import com.jf.cloud.search.constant.EsRenovationProductSortEnum;
import com.jf.cloud.search.manager.ProductSearchManager;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.commons.collections4.CollectionUtils;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 商品搜索
 * @author zz
 * @date 2020/11/16
 */
@RestController("platformSearchSpuController")
@RequestMapping("/p/search")
@Tag(name = "platform-spu列表接口")
public class ProductSearchController {

    @Autowired
    private ProductSearchManager productSearchManager;
    @Autowired
    private ShopDetailFeignClient shopDetailFeignClient;
    @Autowired
    private SupplierDetailFeignClient supplierDetailFeignClient;

    @GetMapping("/page")
    @Operation(summary = "商品管理信息列表（平台端）" , description = "商品管理信息列表（平台端）")
    public ServerResponseEntity<EsPageVO<SpuAdminVO>> adminPage(@Valid EsPageDTO pageDTO, @ParameterObject ProductSearchDTO productSearchDTO) {
        productSearchDTO.setFetchSource(EsConstant.PLATFORM_FETCH_SOURCE);
        EsPageVO<SpuAdminVO> searchPage =  productSearchManager.adminPage(pageDTO, productSearchDTO);
        List<SpuAdminVO> spuAdminVOList = searchPage.getList();
        List<SpuAdminVO> supplierSpuList = spuAdminVOList.stream().filter(s-> Objects.equals(s.getSupplierSpuType(), SupplierSpuType.YES.value())).collect(Collectors.toList());
        List<Long> supplierIds = supplierSpuList.stream().map(SpuAdminVO::getSupplierId).collect(Collectors.toList());
        List<SupplierApiDetailVO> supplierApiDetailVOS = supplierDetailFeignClient.listSupplierDetailBySupplierIds(supplierIds).getData();
        Map<Long, SupplierApiDetailVO> supplierMap = supplierApiDetailVOS.stream().collect(Collectors.toMap(SupplierApiDetailVO::getSupplierId, s -> s));
        //供应商商品的店铺名称
        for(SpuAdminVO supplierSpu : supplierSpuList){
            supplierSpu.setShopName(supplierMap.get(supplierSpu.getSupplierId()).getSupplierName());
        }
        // 店铺名称
        if (CollUtil.isNotEmpty(spuAdminVOList) && spuAdminVOList.size() != 0){
            List<Long> shopIdList = spuAdminVOList.stream( ).map(SpuAdminVO::getShopId).collect(Collectors.toList());
            List<ShopDetailVO> shopDetailVOList = shopDetailFeignClient.listByShopIds(shopIdList).getData();
            Map<Long, List<ShopDetailVO>> shopDetailVoMap = shopDetailVOList.stream().collect(Collectors.groupingBy(ShopDetailVO::getShopId));
            for (SpuAdminVO spuAdminVO : spuAdminVOList) {
                List<ShopDetailVO> shopDetailList = shopDetailVoMap.get(spuAdminVO.getShopId());
                if (Objects.isNull(shopDetailList)){
                    continue;
                }
                spuAdminVO.setShopName(shopDetailList.get(0).getShopName());
            }
        }


        return ServerResponseEntity.success(searchPage);
    }

    @GetMapping("/score_page")
    @Operation(summary = "积分商品搜索（平台端）" , description = "积分商品搜索（平台端）")
    public ServerResponseEntity<EsPageVO<SpuAdminVO>> scorePage(@Valid EsPageDTO pageDTO, @ParameterObject ProductSearchDTO productSearchDTO) {
        productSearchDTO.setFetchSource(EsConstant.PLATFORM_FETCH_SOURCE);
        EsPageVO<SpuAdminVO> searchPage =  productSearchManager.adminPage(pageDTO, productSearchDTO);
        for(SpuAdminVO spuAdminVO : searchPage.getList()){
            if(Objects.equals(spuAdminVO.getSupplierSpuType(), SupplierSpuType.YES.value()) && Objects.isNull(spuAdminVO.getShopName())){
                spuAdminVO.setShopName(spuAdminVO.getSupplierName());
            }
        }
        return ServerResponseEntity.success(searchPage);
    }

    @GetMapping("/tag_page")
    @Operation(summary = "分组商品列表（平台端）" , description = "分组商品列表（平台端）")
    public ServerResponseEntity<EsPageVO<SpuAdminVO>> tagPage(@Valid EsPageDTO pageDTO, @ParameterObject ProductSearchDTO productSearchDTO) {
        productSearchDTO.setFetchSource(EsConstant.PLATFORM_TAG_FETCH_SOURCE);
        EsPageVO<SpuAdminVO> searchPage =  productSearchManager.adminPage(pageDTO, productSearchDTO);
        // 插入序号
        for (SpuAdminVO spuAdminVO : searchPage.getList()) {
            for (SearchSpuTagVO tag : spuAdminVO.getTags()) {
                if (Objects.equals(productSearchDTO.getTagId(), tag.getTagId())) {
                    spuAdminVO.setSeq(tag.getSeq());
                }
            }
            spuAdminVO.setTags(null);
        }
        return ServerResponseEntity.success(searchPage);
    }

    @GetMapping("/renovation_page")
    @Operation(summary = "商品信息列表(平台装修商品列表)" , description = "商品信息列表(平台装修商品列表)")
    public ServerResponseEntity<EsPageVO<ProductSearchVO>> renovationPage(@Valid EsPageDTO pageDTO, @ParameterObject ProductSearchDTO productSearchDTO) {
        Long size = null;
        if(Objects.equals(productSearchDTO.getShowSpuType(),1)){
            if(Objects.equals(productSearchDTO.getEsRenovationSpuSort(), EsRenovationProductSortEnum.CREATE_TIME_ASC.value()) || Objects.equals(productSearchDTO.getEsRenovationSpuSort(),EsRenovationProductSortEnum.CREATE_TIME_DESC.value())){
                productSearchDTO.setSort(productSearchDTO.getEsRenovationSpuSort());
            }else {
                // 获取指定规则的商品ids
                size = getSpuIds(pageDTO, productSearchDTO);
            }
        }
        EsPageVO<ProductSearchVO> searchPage =  productSearchManager.renovationPage(pageDTO, productSearchDTO, size);
        productSearchManager.loadData(productSearchDTO, searchPage.getList());
        return ServerResponseEntity.success(searchPage);
    }


    private Long getSpuIds(EsPageDTO pageDTO, ProductSearchDTO productSearchDTO) {
        Long shopId = Objects.isNull(productSearchDTO.getShopId()) ? 0L :  productSearchDTO.getShopId();
        String key = EsConstant.RENOVATION_PRODUCT_IDS_CACHE + CacheNames.UNION + shopId +
                CacheNames.UNION_KEY + productSearchDTO.getEsTimeRange() + CacheNames.UNION_KEY + productSearchDTO.getEsRenovationSpuSort()
                + CacheNames.UNION_KEY + productSearchDTO.getPrimaryCategoryId();
        if(!RedisUtil.hasKey(key)){
            productSearchManager.addRenovationSpuCache(key,productSearchDTO, shopId, EsConstant.RENOVATION_PRODUCT_IDS_CACHE_TIME);
//            return new ArrayList<>();
        }
        Long size = RedisUtil.getListSize(key);
        long startNum = (long) (pageDTO.getPageNum() - 1) * pageDTO.getPageSize();
        long endNum = (long) pageDTO.getPageNum() * pageDTO.getPageSize() - 1;
        endNum = Math.min(endNum,size - 1);
        List spuIds = RedisUtil.getListRange(key, startNum, endNum);
        productSearchDTO.setSpuIds(spuIds);
        return size;
    }

}
